<script setup lang="ts">
// 商品列表
const products = ref<Product[]>([]);
// 页码
const pageNumber = ref(1);
const route = useRoute();
const props = defineProps<{ keyword?: string }>();

const scrollEle = inject<Ref<HTMLDivElement>>(SCROLL_ELE);
useInfiniteScroll(
  scrollEle,
  () => {
    if (scrollEle) {
      if (data.value && pageNumber.value < data.value.totalPages) {
        pageNumber.value++;
      }
    }
  },
  { distance: 0, interval: 200 },
);

const url = computed(() => {
  if (route.params.categoryId) {
    return `products/category/${route.params.categoryId}?page=${pageNumber.value}&limit=5`;
  } else if (props.keyword) {
    return `products/search?name=${props.keyword}&page=${pageNumber.value}`;
  } else {
    return `products?page=${pageNumber.value}`;
  }
});

const { data, isFetching } = useFetch(url).json<Page<Product>>();

watchEffect(() => {
  if (data.value) {
    if (data.value.currentPage === 1) {
      products.value = data.value.data;
    } else {
      products.value.push(...data.value.data);
    }
  }
});
watch(
  () => props.keyword,
  () => {
    pageNumber.value = 1;
  },
);

onBeforeRouteUpdate(() => {
  pageNumber.value = 1;
});
</script>

<template>
  <div class="product-list">
    <router-link :to="`/products/${item.id}`" class="product-item" v-for="item in products" :key="item.id">
      <div class="img-wrap">
        <img :src="item.image_url" :alt="item.name" />
      </div>
      <h2 class="name">{{ item.name }}</h2>
      <h3 class="price">{{ item.price.toFixed(2) }}</h3>
    </router-link>
  </div>

  <p class="msg" v-if="!isFetching && data?.data.length === 0">---- 没有数据 ----</p>
  <p class="msg" v-if="isFetching">---- 加载中 ----</p>
  <p class="msg" v-if="!isFetching && data?.currentPage == data?.totalPages">---- 已经加载到最后 ----</p>

  <BackTopButton></BackTopButton>
</template>

<style lang="scss" scoped>
.product-list {
  display: grid;
  grid-template-columns: 1fr 1fr;

  .product-item {
    padding: 20rem;

    .img-wrap {
      border: none;
      border-radius: 20rem;
      overflow: hidden;
      box-shadow: 0 0 10rem rgba($color: #000000, $alpha: 0.3);
    }
    .name {
      font-size: 15rem;
      color: var(--light-color);
    }
    .price {
      &::before {
        content: '￥';
      }
    }
  }
}
.msg {
  font-size: 14rem;
  text-align: center;
}
</style>
